package com.ai;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import com.wedata.HttpUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * https://liblibai.feishu.cn/wiki/UAMVw67NcifQHukf8fpccgS5n6d
 * 2.1.2 星流Star-3 Alpha图生图
 */
public class Alpha图生图 {

    //Liblib开放平台域名：
    private static String uri="https://openapi.liblibai.cloud"; //（无法直接打开，需配合密钥访问）

    private static String accessKey = "ryRANn78-tig9nhO2yeuFA";
    // API访问密钥
    private static String secretKey = "N7KMokPXrXU21l19wz0YEodnzVehpKar";

    public static void main(String[] args) {
        //img2img("url","1 girl,lotus leaf,masterpiece,best quality,finely detail,highres,8k,beautiful and aesthetic,no watermark,");
        //text2img();
        query("1c040525b9144dc6abe6830203f4b7c9");
    }

    /**
     * 换脸大手术
     * @return
     */
    private static String text2img(){
        String url = uri + makeSign("/api/generate/webui/text2img");
        JSONObject header = new JSONObject();
        JSONObject body = new JSONObject();
        body.set("templateUuid", "7d888009f81d4252a7c458c874cd017f");//换脸模板
        JSONObject generateParams = new JSONObject();
        //generateParams.set("checkPointId",  "0ea388c7eb854be3ba3c6f65aac6bfd3");   // 仅 XL模型支持人像换脸
        generateParams.set("prompt",  "Asian portrait); A young woman wearing jeans);  background is a park);   best quality);  ultra resolution");   // 选填
        generateParams.set("width",  768);   // 宽，必填
        generateParams.set("height",  1088);   // 高，必填

        //以下参数可不传
        //generateParams.set("sampler", 20);   // 默认DPM++ 2M SDE Karras
        //generateParams.set("steps",  35);   // 默认35步
        //generateParams.set("cfgScale",  2.0);
        //generateParams.set("imgCount",  1);   // 图片数量，默认1张

        List<JSONObject> controlNet = new ArrayList<>();
        JSONObject sourceImg = new JSONObject();//设置要用的人像人脸
        sourceImg.set("unitOrder", 2); // 第一步：先识别要用的人像人脸
        sourceImg.set("sourceImage", "https://twedata.gymcity.com.cn/h5/AAAA.jpg");

        sourceImg.set("width", 682); // 参考图宽度
        sourceImg.set("height", 1024); // 参考图高度

        JSONObject targetImg = new JSONObject();//设置面部朝向的人像参考图
        targetImg.set("unitOrder", 1); // 第二步：再识别要参考的人物面部朝向
        targetImg.set("sourceImage", "https://twedata.gymcity.com.cn/h5/BBB.webp");
        targetImg.set("width", 768); // 参考图宽度
        targetImg.set("height", 1088); // 参考图高度
        controlNet.add(targetImg);
        controlNet.add(sourceImg);
        generateParams.set("controlNet",controlNet);
        body.set("generateParams",generateParams);

        JSONObject jsonObject = HttpUtils.sendPost(url,header,body);
        //{"msg":"图片包含违规内容: field: [controlNet[0].sourceImage]","code":100031,"data":null}
        //{"msg":"","code":0,"data":{"generateUuid":"c624660600894b048b4216cab317eefc"}}
        //{"msg":"","code":0,"data":{"generateUuid":"de83934eeb8c42ce83649ca81289bb7b"}}
        //{"msg":"","code":0,"data":{"generateUuid":"1c040525b9144dc6abe6830203f4b7c9"}}
        System.out.println(jsonObject);
        return jsonObject.getStr("generateUuid");
    }
    /**
     * Alpha图生图
     * @return
     */
    private static String img2img(String img,String prompt){
        String url = uri + makeSign("/api/generate/webui/img2img/ultra");
        JSONObject header = new JSONObject();
        JSONObject body = new JSONObject();
        //body.set("templateUUID", "5d7e67009b344550bc1aa6ccbfa1d7f4");//Alpha文生图
        //body.set("templateUUID", "07e00af4fc464c7ab55ff906f8acf1b7");//Alpha图生图
        body.set("templateUuid", "07e00af4fc464c7ab55ff906f8acf1b7");//Alpha图生图
        JSONObject generateParams = new JSONObject();
        generateParams.set("prompt",prompt);
        generateParams.set("sourceImage","https://twedata.gymcity.com.cn/h5/bb22.jpg");
        //{"msg":"","code":0,"data":{"generateUuid":"f8cef23fd72748e788c690fec51b7908"}}
        //{"msg":"","code":0,"data":{"generateUuid":"cad9e47fea444edaac1c6810760d5181"}}
        generateParams.set("imgCount",1);
        JSONObject controlnet = new JSONObject();
        controlnet.set("controlType","IPAdapter");
        controlnet.set("controlImage","https://twedata.gymcity.com.cn/h5/cc33.png");
        generateParams.set("controlnet",controlnet);//参考的图片

        body.set("generateParams",generateParams);


        JSONObject jsonObject = HttpUtils.sendPost(url,header,body);
        System.out.println(jsonObject);
        //{"msg":"图片包含违规内容: field: [sourceImage]","code":100031,"data":null}
        //{"msg":"图片下载失败: https: //q2.itc.cn/q_70/images01/20240304/689c3259171141b98b614f14179e7975.jpeg","code":100032,"data":null}
        return jsonObject.getStr("generateUuid");
    }

    /**
     * 查询生图结果
     * @return
     */
    private static String query(String generateUuid){
        String url = uri + makeSign("/api/generate/webui/status");
        JSONObject header = new JSONObject();
        JSONObject body = new JSONObject();
        body.set("generateUuid", generateUuid);

        JSONObject jsonObject = HttpUtils.sendPost(url,header,body);
        System.out.println(jsonObject);
        //{"msg":"","code":0,"data":{"percentCompleted":0.5,"images":[],"pointsCost":null,"generateMsg":null,"generateStatus":2,"accountBalance":null,"generateUuid":"0c3b137dd20d4932aa7384579f40c416"}}
        //{"msg":"","code":0,"data":{"percentCompleted":1,"images":[{"seed":1904869961,"imageUrl":"https://liblibai-tmp-image.liblib.cloud/img/374e465c3d774c148e0f6748cc5f11ae/e9763371f6de47e61249c69471e9f4b4952f637de1e2c9f4afc3850ad582db18.png","auditStatus":3}],"pointsCost":33,"generateMsg":null,"generateStatus":5,"accountBalance":467,"generateUuid":"f8cef23fd72748e788c690fec51b7908"}}
        return jsonObject.getStr("generateUuid");
    }
    /**
     * 生成请求签名
     * 其中相关变量均为示例，请替换为您的实际数据
     */
    public static String makeSign(String uri) {
        // 请求API接口的uri地址
        //String uri = "/api/generate/webui/text2img";
        // 当前毫秒时间戳
        Long timestamp = System.currentTimeMillis();
        // 随机字符串
        String signatureNonce = RandomStringUtils.randomAlphanumeric(10);
        // 拼接请求数据
        String content = uri + "&" + timestamp + "&" + signatureNonce;


        try {
            // 生成签名
            SecretKeySpec secret = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(secret);

            String signature = Base64.encodeBase64URLSafeString(mac.doFinal(content.getBytes()));
            //?AccessKey=KIQMFXjHaobx7wqo9XvYKA&Signature=test1232132&Timestamp=1725458584000&SignatureNonce=random1232
            StringBuffer sb = new StringBuffer(uri);
            sb.append("?AccessKey=").append(accessKey);
            sb.append("&Signature=").append(signature);
            sb.append("&Timestamp=").append(timestamp);
            sb.append("&SignatureNonce=").append(signatureNonce);

            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("no such algorithm");
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }
}
